#此功能用于修改配置文件

#读取config.json文件
import json
import os
import sys
import tempfile
from decimal import Decimal, ROUND_HALF_UP

import openpyxl

from entity.calculate_table_entity import CalculateTableEntity
from ut.read_config import read_computation_sheet_config, get_read_computation_path
from ut.windows_ui import show_warning, file_path_query, input_file_name, select_folder



# 读取计算表数据
def read_computation_sheet_date():
    try:
        config=read_computation_sheet_config()
        adrr=config.get("config",[{}])[0].get("computation_sheet",{}).get("address")
        sheet_name=config.get("config",[{}])[0].get("computation_sheet",{}).get("sheet_name")
        wb=openpyxl.load_workbook(adrr,data_only=True)
        sheet=wb[sheet_name]
        ls=[]
        for row in sheet.iter_rows(min_row=2,min_col=1):
            if row[0].value is None or row[1].value is None or row[2].value is None:
                continue
            ls.append(
                CalculateTableEntity(row[0].value,
                                     int(row[1].value),
                                     Decimal(row[2].value)
                                     ))
        return ls
    except Exception as e:
        show_warning(f"计算表读取失败，请检查配置文件！{e}")
        exit(e)


# 修改配置文件
def set_computation_sheet_config():
    adrr=file_path_query("请选择计算表地址：")
    sheet_name=input_file_name("请输入计算表sheet名称：")
    config=read_computation_sheet_config()
    if adrr is None or sheet_name is None or adrr=="" or sheet_name=="":
        show_warning("计算表和sheet页不能为空！")
        return

    config["config"][0]["computation_sheet"]["address"]=adrr
    config["config"][0]["computation_sheet"]["sheet_name"]=sheet_name

    try:
        with open(get_read_computation_path(),'w',encoding='utf-8') as f:
            json.dump(config,f,ensure_ascii=False,indent=4)
        show_warning("计算表配置修改成功！")
    except Exception as e:
        print(e)



# if __name__ == '__main__':
#     read_web_config()